package com.feinno.urcs.group.dao;

import com.feinno.database.DataRow;
import com.feinno.database.DataTable;
import com.feinno.database.Database;
import com.feinno.urcs.group.GroupConfiguration;
import com.feinno.urcs.group.api.FXUserIndexService;
import com.feinno.urcs.group.api.UserGroupListDao;
import com.feinno.urcs.group.entity.GroupIndex;
import com.feinno.urcs.group.fxdb.FXPoolService;
import com.feinno.urcs.group.fxdb.PooledDatabaseLoader;
import com.feinno.urcs.group.interop.entity.FXCatalogIndex;
import com.feinno.urcs.types.MobileNo;
import org.helium.framework.annotations.FieldSetter;
import org.helium.framework.annotations.ServiceImplementation;
import org.helium.framework.annotations.ServiceSetter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by honghao on 5/4/15.
 * <p>
 * <p>
 * 操作getDatabase(index).GRP_UserGroups 表
 */
@ServiceImplementation
public class UserGroupListDaoImplFetion implements UserGroupListDao {
	private static final Logger LOGGER = LoggerFactory.getLogger(UserGroupListDaoImplFetion.class);

	//TODO 后续可能需要增加对GroupType 的 判断.
	@FieldSetter("${GGRPDB}")
	private Database ggrpDb;

	@FieldSetter(value = "${GRPDB_POOLS_XML}", loader = PooledDatabaseLoader.class)
	private Map<Integer, Database> grpdbs;
	@ServiceSetter
	private FXUserIndexService fetionIndexService;
	@ServiceSetter
	private FXPoolService poolService;


	/**
	 * 获取指定PhysicalPool的getDatabase(index)
	 * @param index 群索引
	 * @return 返回Database连接
	 * @throws SQLException
	 */
	private Database getDatabase(GroupIndex index) throws SQLException {
		int logicPool = index.getLogicalPool();
		if (logicPool == 0) {
			String sql = "SELECT LogicPool FROM GGRP_SearchGroup WHERE GroupId = ?";
			DataTable dt = ggrpDb.executeTable(sql, index.getGroupId());
			logicPool = dt.getRow(0).getInt("LogicPool");

		}
		int poolid = poolService.getPhyicalPool(logicPool);
		return getDatabase(poolid);
	}
	private Database getDatabase(int  logicPool) throws SQLException {
		int poolid = poolService.getPhyicalPool(logicPool);
		return grpdbs.get(poolid);
	}


	@Override
	public boolean canCreateGroup(MobileNo mobileNo) throws Exception {
		int count = getCreateGroupCount(mobileNo);
		return count < GroupConfiguration.INSTANCE.getCreateGroupMaxCount();
	}

	@Override
	public int getGroupCount(MobileNo mobileNo) throws Exception {
		int logicPool = fetionIndexService.getLogicPool(mobileNo);

		String sql = "select count(GroupId) from GRP_UserGroups where MobileNo = ? ";
		DataTable dt = getDatabase(logicPool).executeTable(sql, mobileNo.toString(), 1);
		int count = 0;
		if (dt.getRowCount() > 0) {
			count = dt.getRow(0).getInt(1);
		}
		return count;
	}

	@Override
	public int getCreateGroupCount(MobileNo mobileNo) throws Exception {
		int logicPool = fetionIndexService.getLogicPool(mobileNo);
		String sql = "select count(GroupId) from GRP_UserGroups where MobileNo = ? and Identity = ?";
		DataTable dt = getDatabase(logicPool).executeTable(sql, mobileNo.toString(), 1);
		int count = 0;
		if (dt.getRowCount() > 0) {
			count = dt.getRow(0).getInt(1);
		}
		return count;
	}


	@Override
	public List<GroupIndex> getUserGroupList(MobileNo mobileNo) throws Exception {
		int logicPool = fetionIndexService.getLogicPool(mobileNo);
		String sql = "select Identity,GroupId,GroupLogicalPool from GRP_UserGroups where MobileNo = ?";
		DataTable dt = getDatabase(logicPool).executeTable(sql, mobileNo.toString());
		List<GroupIndex> groupList = new ArrayList<GroupIndex>();
		for (DataRow dr : dt.getRows()) {
			if (dr.getInt("Identity") == 61) {
				continue;
			}
			GroupIndex index = new GroupIndex();
			index.setGroupId(dr.getInt("GroupId"));
			index.setLogicalPool(dr.getInt("GroupLogicalPool"));
			groupList.add(index);
		}
		return groupList;
	}


	@Override
	public void updateUserGroupIdentity(MobileNo mobileNo, GroupIndex index, int identity) throws Exception {
		String sql = "update GRP_UserGroups set Identity =? where GroupId =? and MobileNo=?";
		LOGGER.info(String.format("updateGroupId=%s\tmobile=%s\tidentity=%s",index.getGroupId(),mobileNo,identity));
		FXCatalogIndex userIndex = fetionIndexService.getFXCatalogIndex(mobileNo);
		getDatabase(userIndex.getLogicalPoolId()).executeNonQuery(sql, identity, index.getGroupId(), mobileNo.toString());

	}

	@Override
	public void updateUserGroupIdentityWithUserId(int userid, GroupIndex index, int identity) throws Exception {
		String sql = "update GRP_UserGroups set Identity =? where GroupId =? and UserId=?";
		LOGGER.info(String.format("updateGroupId=%s\tmobile=%s\tidentity=%s",index.getGroupId(),userid,identity));
		int logicalPoolId = fetionIndexService.getLogicPoolByUserId(userid);
		getDatabase(logicalPoolId).executeNonQuery(sql, identity, index.getGroupId(), userid);
	}

	@Override
	public void insertUserGroupList(MobileNo mobileNo, GroupIndex index, int identity) throws Exception {
		//TODO 需要查询UserID

		FXCatalogIndex userIndex = fetionIndexService.getFXCatalogIndex(mobileNo);
		String sql = "insert into GRP_UserGroups(GroupId,GroupLogicalPool,MobileNo,UserId,GroupType,Identity) values(?,?,?,?,?,?)";

		String getMemberSql = "select * from GRP_UserGroups where GroupId = ? and MobileNo = ?";
		DataTable dataTable = getDatabase(userIndex.getLogicalPoolId()).executeTable(getMemberSql, index.getGroupId(), mobileNo.toString());
		if (dataTable.getRowCount() != 0) {
			// 处理重复写入数据的逻辑
			LOGGER.info(String.format("insertUserGroupList Member exist, groupId=%s member=%s ", index.getGroupId(), mobileNo));
			return;
		}
		getDatabase(userIndex.getLogicalPoolId()).executeNonQuery(sql, index.getGroupId(), index.getLogicalPool(), mobileNo.toString(), userIndex.getUserId(), 1, identity);
	}


	@Override
	public void deleteUserGroupList(MobileNo mobileNo, GroupIndex index) throws Exception {
		String sql = "delete from GRP_UserGroups where MobileNo = ? and GroupId = ?";
		FXCatalogIndex userIndex = fetionIndexService.getFXCatalogIndex(mobileNo);
		getDatabase(userIndex.getLogicalPoolId()).executeNonQuery(sql, mobileNo.toString(), index.getGroupId());
	}

	@Override
	public void dismissGroup(GroupIndex index) throws SQLException {
		String sql = "delete from GRP_UserGroups where GroupId = ?";
		getDatabase(index).executeNonQuery(sql, index.getGroupId());
		throw new RuntimeException("F**K" );
	}
}
